<template>
  <div>
    <h2>图表1</h2>
    <div class="chart" ref="oneChart">容纳后期的图表</div>
  </div>
</template>

<script>
// 1引用inject获取全局echarts
import { inject, onMounted, reactive } from "vue";
import { ref } from "vue";
// import { getCurrentInstance } from 'vue'
export default {
  setup() {
    let $echarts = inject("echarts");
    let $http = inject("axios");
    // 获取页面的实例对象
    const oneChart = ref(null);
    async function getState() {
      data = await $http({
        url: "/one/data",
      });
    }
    let data = reactive({});
    let xdata = reactive([]);
    let ydata = reactive([]);
    function setData() {
      xdata = data.data.chartData.chartData.map((v) => v.title);
      ydata = data.data.chartData.chartData.map((v) => v.num);
    }
    onMounted(() => {
      // let myChart = $echarts.init(document.querySelector(".chart"));//tagDom
      let myChart = $echarts.init(oneChart.value);
      getState().then(() => {
        setData();
        myChart.setOption({
          grid: {
            top: "3%",
            left: "1%",
            right: "6%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
            axisLine: {
              lineStyle: {
                color: "#fff",
              },
            },
          },
          yAxis: {
            type: "category",
            data: xdata,
            axisLine: {
              lineStyle: {
                color: "#fff",
              },
            },
          },
          series: [
            {
              type: "bar",
              data: ydata,
              itemStyle: {
                normal: {
                  // 如果传递数组 则需要传递四个元素
                  barBorderRadius: [0, 20, 20, 0],
                  // 渐变色
                  color: new $echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    {
                      offset: 0,
                      color: "#005eaa",
                    },
                    {
                      offset: 0.5,
                      color: "#330ca8",
                    },
                    {
                      offset: 1,
                      color: "#cda819",
                    },
                  ]),
                },
              },
            },
          ],
        });
      });
    });
    return {
      getState,
      data,
      xdata,
      ydata,
      setData,
      oneChart,
    };
  },
};
</script>

<style scoped>
h2 {
  /* 48像素 */
  height: 0.6rem;
  color: #fff;
  line-height: 0.6rem;
  text-align: center;
  font-size: 0.25rem;
}
.chart {
  /* 高度360 */
  height: 4.5rem;
}
</style>